package cn.gailvlun.gll.presentation.emotion.widget

import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.RadioButton
import android.widget.RadioGroup


class MultiLineRadioGroup : RadioGroup {
    constructor(context: Context?) : super(context)
    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)

    private var mOnCheckedChangeListener: OnCheckedChangeListener? = null
    override fun addView(child: View?, index: Int, params: ViewGroup.LayoutParams?) {
        if (child is LinearLayout) {
            val childCount = child.childCount
            for (i in 0 until childCount) {
                val view = child.getChildAt(i)
                if (view is RadioButton) {
                    val radioButton = view as RadioButton
                    radioButton.setOnTouchListener { view, event ->
                        radioButton.isChecked = true
                        checkRadioButton(radioButton)
                        if (mOnCheckedChangeListener != null) {
                            mOnCheckedChangeListener!!.onCheckedChanged(this@MultiLineRadioGroup, radioButton.id);
                        }
                        return@setOnTouchListener true

                    }
                }

            }
        }
        super.addView(child, index, params)

    }

    override fun setOnCheckedChangeListener(listener: OnCheckedChangeListener) {
        mOnCheckedChangeListener = listener
    }

    private fun checkRadioButton(radioButton: RadioButton) {
        var child: View
        val radioCount = childCount
        for (i in 0 until radioCount) {
            child = getChildAt(i)
            if (child is RadioButton) {
                if (child == radioButton) {
                    
                } else {
                    (child as RadioButton).isChecked = false;
                }
            } else if (child is LinearLayout) {
                val childCount = (child as LinearLayout).childCount

                (0 until childCount)
                        .map { (child as LinearLayout).getChildAt(it) }
                        .filterIsInstance<RadioButton>()
                        .map { it as RadioButton }
                        .forEach {
                            if (it == radioButton) {
                                
                            } else {
                                it.isChecked = false
                            }
                        }
            }
        }

    }
}
